# coding: utf-8
import logging
import os
import tempfile

from flask import Flask, request, make_response, send_file
from gevent.pywsgi import WSGIServer
from werkzeug import utils

from sql.gen import gen_sql

ALLOWED_EXTENSIONS = set(['xls', 'xlsx'])

app = Flask(__name__)
# 上传文件限制为最大 16 MB
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            try:
                filename = utils.secure_filename(file.filename)
                abs_filename = os.path.join(tempfile.gettempdir(), filename)
                file.save(abs_filename)
                result_file = tempfile.mkstemp(suffix=".sql")[1]
                gen_sql(abs_filename, result_file)
                response = make_response(send_file(result_file, as_attachment=True))
                response.headers["Content-Disposition"] = "attachment; filename={}".format(
                    os.path.basename(result_file).encode().decode('utf-8'))
                return response
            except Exception as e:
                logging.error("exception %s", e)
                return f"{e}"
    return '''
        <!doctype html>
        <title>上传指标树电子表格</title>
        <h1>上传指标树电子表格(.xls/.xlsx)，生成Oracle数据插入脚本。</h1>
        <h2>上传文件最大大小是16MB</h2>
        <form action="" method=post enctype=multipart/form-data>
          <p><input type=file name=file>
             <input type=submit value=Upload>
        </form>
        '''


if __name__ == '__main__':
    http_server = WSGIServer(listener=('0.0.0.0',5000), application=app)
    http_server.serve_forever()
